package com.example.exam.dao;

import com.example.exam.entity.Student;
import com.example.exam.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 学生数据访问对象
 */
public class StudentDAO {
    private QueryRunner queryRunner = new QueryRunner();
    
    // 根据学号查询学生
    public Student getStudentById(String studentId) {
        String sql = "SELECT * FROM students WHERE student_id = ?";
        try (Connection conn = DBUtil.getConnection()) {
            return queryRunner.query(conn, sql, new BeanHandler<>(Student.class), studentId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    // 验证学生登录
    public boolean validateLogin(String studentId, String password) {
        String sql = "SELECT COUNT(*) FROM students WHERE student_id = ? AND password = ?";
        try (Connection conn = DBUtil.getConnection()) {
            Long count = queryRunner.query(conn, sql, new ScalarHandler<>(), studentId, password);
            return count != null && count > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    // 修改学生密码
    public boolean updatePassword(String studentId, String oldPassword, String newPassword) {
        // 先验证旧密码是否正确
        if (!validateLogin(studentId, oldPassword)) {
            return false;
        }
        
        String sql = "UPDATE students SET password = ? WHERE student_id = ?";
        try (Connection conn = DBUtil.getConnection()) {
            int rows = queryRunner.update(conn, sql, newPassword, studentId);
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    // 更新学生信息
    public boolean updateStudentInfo(Student student) {
        String sql = "UPDATE students SET major = ?, grade = ?, phone = ?, email = ?, address = ? " +
                     "WHERE student_id = ?";
        try (Connection conn = DBUtil.getConnection()) {
            int rows = queryRunner.update(conn, sql, 
                    student.getMajor(), 
                    student.getGrade(), 
                    student.getPhone(), 
                    student.getEmail(), 
                    student.getAddress(),
                    student.getStudentId());
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}    